package it.blog.controller;

import javax.servlet.http.*;
import javax.servlet.*;
import javax.xml.ws.wsaddressing.W3CEndpointReference;

import java.io.*;

import it.blog.stub.*;


public class Login extends HttpServlet {

	private static final long serialVersionUID = 4674804026617429475L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
	}	


	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
		HttpSession session =  request.getSession();
		String sessionId= session.getId();
		BlogPortal bp = new BlogPortalService().getPort(BlogPortal.class);

		//Ottengo lo username e la password inseriti dall'utente
		String username=request.getParameter("username");
		String password=request.getParameter("password");


		W3CEndpointReference ref=bp.createUserSession(username, password,sessionId);


		if(ref!=null) {
			
			session.setAttribute("ref", ref);
			session.setAttribute("loginFail",false);
			User user=bp.getUserSession(sessionId);
			session.setAttribute("user",user);

			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));
		}
		else {
			//L'utente ha immesso credenziali non valide, quindi il login non e' andato a buon fine
			session.setAttribute("loginFail",true);
			//Rimando alla pagina default.jsp cancellando la richiesta corrente
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));

		}

	}

}
